package com.compass.doctor.ui.home

import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.PersistableBundle
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MarkerOptions
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnLocationButtonCallBack
import com.compass.doctor.databinding.ActivityMedicalCareOrderBinding
import com.compass.doctor.dialog.LocationDialog
import com.compass.doctor.preview.PreviewPicActivity
import com.compass.doctor.ui.home.adapter.ExtraConsumablesAdapter
import com.compass.doctor.ui.home.adapter.OrderLogAdapter
import com.compass.doctor.ui.home.adapter.PatientPictureAdapter
import com.compass.doctor.ui.home.viewmodel.MedicalCareViewModel
import com.compass.framework.constant.KEY_ORDER_ID
import com.compass.framework.constant.REFRESH_CARE
import com.compass.framework.constant.REFRESH_RX
import com.compass.framework.decoration.NormalItemDecoration
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.visible
import com.compass.framework.glide.setUrlCircle
import com.compass.framework.helper.CompassAppHelper
import com.compass.framework.model.Address
import com.compass.framework.model.ConsumableOrder
import com.compass.framework.model.Log
import com.compass.framework.model.MedicalCareOrder
import com.compass.framework.model.NurseLog
import com.compass.framework.model.NursePersonComment
import com.compass.framework.model.NurseProjectComment
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.BigDecimalUtils
import com.compass.framework.utils.DateUtils
import com.compass.framework.utils.FullyGridLayoutManager
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.ViewUtils
import com.compass.framework.utils.dpToPx
import com.compass.framework.utils.getStringFromResource
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.entity.LocalMedia
import com.netease.yunxin.kit.common.ui.dialog.BaseBottomChoiceDialog
import com.netease.yunxin.kit.common.ui.dialog.BottomChoiceDialog
import com.netease.yunxin.kit.locationkit.MapNavigator


/**
 * Description： 医护上门--订单详情
 * Date:2023/12/31 18:49
 */
class MedicalCareOrderActivity : BaseVBActivity<ActivityMedicalCareOrderBinding>() {

    companion object {
        fun start(context: Context, orderId: String) {
            val intent = Intent(context, MedicalCareOrderActivity::class.java)
            intent.putExtra(KEY_ORDER_ID, orderId)
            context.startActivity(intent)
        }
    }

    private lateinit var careOrder: MedicalCareOrder
    private lateinit var mLocationOption: AMapLocationClientOption
    private lateinit var mLocationClient: AMapLocationClient

    //声明定位回调监听器
    private var mLocationListener = AMapLocationListener { amapLocation ->
        if (this::careOrder.isInitialized) {
            amapLocation?.let {
                if (amapLocation.errorCode == 0) {
                    dismissLoading()
                    LocationDialog.Builder(
                        this,
                        amapLocation,
                        careOrder,
                        onLocationButtonCallBack
                    ).show()
                } else {
                    showToast("定位失败请检查手机定位功能")
                }
            }

        }
        dismissLoading()
    }
    private val onLocationButtonCallBack = object : OnLocationButtonCallBack {
        override fun onButtonCallBack(id: String, status: String, lat: Double, lot: Double) {
            showLoading()
            //{"label":"出发","value":"3"},{"label":"到达","value":"4"},{"label":"完成","value":"5"}
            when (status) {
                "3" -> {
                    medicalCareViewModel.nurseDeparted(id, lat, lot)
                }

                "4" -> {
                    medicalCareViewModel.nurseArrive(id, lat, lot)
                }
            }
        }
    }
    private lateinit var aMap: AMap
    private lateinit var extraConsumablesAdapter: ExtraConsumablesAdapter
    private lateinit var orderLogAdapter: OrderLogAdapter
    private var pics: ArrayList<String> = ArrayList()
    private lateinit var picAdapter: PatientPictureAdapter
    private val medicalCareViewModel: MedicalCareViewModel by viewModels()
    private var orderId: String = ""
    override fun initView(savedInstanceState: Bundle?) {
        mBinding.mapView.onCreate(savedInstanceState)
        orderId = intent.getStringExtra(KEY_ORDER_ID)!!
        picAdapter = PatientPictureAdapter(1)
        orderLogAdapter = OrderLogAdapter()
        extraConsumablesAdapter = ExtraConsumablesAdapter()
        picAdapter.onItemClickListener = { _: View, position: Int ->
            var loacls = ArrayList<LocalMedia>()
            var localMedia: LocalMedia
            for (pic in pics) {
                localMedia = LocalMedia()
                localMedia.path = pic
                loacls.add(localMedia)
            }
            if (loacls.isNotEmpty()) {
                PreviewPicActivity.start(this, position, loacls)
            }
        }


    }

    override fun intListener() {
        mBinding.tvConnectionPatient.onClick {
            //联系患者（外呼）

            CommonMessageDialog.Builder(this)
                .setTitle(getStringFromResource(com.compass.framework.R.string.dialog_tips_title))
                .setMessage("是否立即呼叫患者？确定后平台会立即呼叫患者，患者接通后会再次呼叫您，请您留意接听电话（电话为029开头）。")
                .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))

                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    medicalCareViewModel.nurseCall(orderId)
                    it?.dismiss()
                }.create().show()

        }
        mBinding.tvContactOnline.onClick {
            //im联系患者（形式待定）
            showToast("im联系患者")
        }


        mBinding.tvSubmit.onClick {
            if (this::careOrder.isInitialized) {
                when (careOrder.status) {
                    "5" -> {
                        //完成订单
                        MedicalCareCompleteOrderActivity.start(this, orderId, careOrder)
                    }

                    else -> {
                        locationIsGranted()
                    }
                }
            }

        }

    }

    //{"label":"出发","value":"3"},{"label":"到达","value":"4"},{"label":"完成","value":"5"}
    override fun initData() {
        showLoading()
        medicalCareViewModel.getMedicalCareOrderDetails(orderId)
        medicalCareViewModel.orderDetailsLiveData.observe(this) {
            dismissLoading()
            careOrder = it
            setButtonStatus(careOrder.status)
            setPatientInfo(careOrder)
            setNurseInfo(careOrder.nurseLog)
            setOrderLog(careOrder.log)
            setServiceEvaluation(careOrder.nurseProjectCommentRespVO,careOrder.nursePersonCommentRespVO)

        }
        //获取耗材订单
        medicalCareViewModel.getConsumableOrder(orderId)
        medicalCareViewModel.consumableOrderLiveData.observe(this) {
            it?.let { orders ->
                setExtraMedicalConsumable(orders)
            }


        }

        medicalCareViewModel.departLiveData.observe(this) {
            dismissLoading()
            medicalCareViewModel.getMedicalCareOrderDetails(orderId)
            LiveDataBus.get().with(REFRESH_CARE).postValue(REFRESH_CARE)
            LiveDataBus.get().with(REFRESH_RX).postValue(REFRESH_RX)
        }
        medicalCareViewModel.reachLiveData.observe(this) {
            dismissLoading()
            medicalCareViewModel.getMedicalCareOrderDetails(orderId)
            LiveDataBus.get().with(REFRESH_CARE).postValue(REFRESH_CARE)
        }

        medicalCareViewModel.callLiveData.observe(this) {
            showToast("正在为您呼叫患者，请稍后")
        }

        LiveDataBus.get().with(REFRESH_CARE, String::class.java).observe(this) {
            dismissLoading()
            medicalCareViewModel.getMedicalCareOrderDetails(orderId)
        }

    }

    private fun setButtonStatus(status: String?) {

        when (status) {
            "3" -> {
                mBinding.tvSubmit.text = "出发"
                mBinding.llAppointmentTime.gone()
                mBinding.llConnection.visible()
                mBinding.llBottomBtn.visible()
//                mBinding.tvSubmit.background= getDrawableResource(R.drawable.btn_shape_orange_50)
            }

            "4" -> {
                mBinding.tvSubmit.text = "到达"
                mBinding.llAppointmentTime.gone()
                mBinding.llConnection.visible()
                mBinding.llBottomBtn.visible()
//                mBinding.tvSubmit.background= getDrawableResource(R.drawable.btn_shape_blue_50)
            }

            "5" -> {
                mBinding.tvSubmit.text = "完成"
                mBinding.llAppointmentTime.gone()
                mBinding.llConnection.visible()
                mBinding.llBottomBtn.visible()
//                mBinding.tvSubmit.background= getDrawableResource(R.drawable.btn_shape_green_50)
            }

            else -> {
                mBinding.llAppointmentTime.visible()
                mBinding.llConnection.gone()
                mBinding.llBottomBtn.gone()
            }
        }

    }


    private fun setPatientInfo(order: MedicalCareOrder) {
        mBinding.apply {
            tvAppointmentTime.text =
                DateUtils.conversionTime(order.appointmentTime, DateUtils.FORMAT_TWO)
            order.address?.let { setMap(it) }
            ivHead.setUrlCircle(order.patientAvatar)
            patientName.text = order.patientName
            usefulSex.text = order.getSexString()
            usefulAge.text = order.patientAge
            nurseName.text = order.nurseName
            tvOrderNumber.text = order.id
            tvDoctor.text = order.doctorName
            tvPayTime.text = DateUtils.conversionTime(order.successTime, DateUtils.FORMAT_TWO)
            tvPayPrice.text = "￥${BigDecimalUtils.divide(order.payPrice)}"
            tvDiseaseDescriptionText.text = order.diseaseDescriptionText
            tvHospitalizedStatus.text = if (order.hospitalizedStatus == "1") "是" else "否"
        }

    }


    /**
     * 设置护理进度/患者体征
     */
    private fun setNurseInfo(nurseLog: NurseLog?) {

        nurseLog?.let {
            mBinding.tvTemperature.text = "${it.temperature}°C"
            mBinding.tvBreathing.text = it.breathing
            mBinding.tvHeartRate.text = it.heartRate
            mBinding.tvBloodPressure.text = "${it.sbp}/${it.dbp}"
            mBinding.tvControlsLogs.text = it.log
            mBinding.recyclerControls.apply {
                val manager = FullyGridLayoutManager(
                    this@MedicalCareOrderActivity,
                    4, FullyGridLayoutManager.VERTICAL, false
                )
                layoutManager = manager
                itemAnimator?.let {
                    (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
                }
                adapter = picAdapter
            }
            pics = it.img as ArrayList<String>

            picAdapter.setData(if (pics.size > 4) pics.subList(0, 4) else pics)
            mBinding.llPatientSigne.visible()
            mBinding.llControlsLogs.visible()

        } ?: kotlin.run {
            mBinding.llPatientSigne.gone()
            mBinding.llControlsLogs.gone()

        }

    }


    /**
     * 设置额外耗材
     */
    private fun setExtraMedicalConsumable(orders: MutableList<ConsumableOrder>) {
        if (orders.isNotEmpty()) {

            mBinding.recyclerExtra.apply {
                layoutManager = LinearLayoutManager(context)
                addItemDecoration(NormalItemDecoration().apply {
                    setBounds(top = dpToPx(10), bottom = dpToPx(10))

                })
                adapter = extraConsumablesAdapter
            }
            extraConsumablesAdapter.setData(orders)
            mBinding.llExtra.visible()

        } else {
            mBinding.llExtra.gone()

        }
    }

    /**
     * 设置订单日志
     */
    private fun setOrderLog(log: MutableList<Log>?) {
        log?.let {
            mBinding.llOrderLog.visible()

            mBinding.recyclerLog.apply {
                layoutManager = LinearLayoutManager(this@MedicalCareOrderActivity)
                adapter = orderLogAdapter
            }
            orderLogAdapter.setData(it)

        } ?: kotlin.run {
            mBinding.llOrderLog.gone()


        }

    }

    /**
     * 设置服务评价
     */
    private fun setServiceEvaluation(
        projectComment: NurseProjectComment?,
        personComment: NursePersonComment?
    ) {
        projectComment?.let {
            mBinding.llServiceEvaluation.visible()
            mBinding.projectEval.text = it.projectEval
            mBinding.projectNumber.text = "${it.projectGrade}分"
            mBinding.projectGrade.starProgress=it.projectGrade

            personComment?.let { person ->
                mBinding.personEval.text = person.personEval
                mBinding.nurseGrade.starProgress=person.nurseGrade
                mBinding.personMannerGrade.starProgress=person.personMannerGrade
                mBinding.personSpeed.starProgress=person.personSpeed
                mBinding.nurseNumber.text = "${person.nurseGrade}分"
                mBinding.personMannerNumber.text = "${person.personMannerGrade}分"
                mBinding.personNumber.text = "${person.personSpeed}分"

            }


        } ?: kotlin.run {
            mBinding.llServiceEvaluation.gone()


        }

    }

    private fun setMap(address: Address) {
        mBinding.tvAddress.text = address.address
        mBinding.tvAddress.onClick {
            jumpOutMap(address)
        }
        aMap = mBinding.mapView.map
        //不显示缩放按钮
        aMap.uiSettings.isZoomControlsEnabled = false
        //控制比例尺控件是否显示
        aMap.uiSettings.isScaleControlsEnabled = false
        //禁止所有手势
        aMap.uiSettings.setAllGesturesEnabled(false)
        ViewUtils.setClipViewCornerRadius(mBinding.mapView, dpToPx(5))
        var coordinates = LatLng(address.getLat(), address.getLon())
//        var coordinates = LatLng(34.14652, 108.841896)//测试坐标

        aMap.moveCamera(CameraUpdateFactory.changeLatLng(coordinates))//移动到指定坐标
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15f));
        aMap.addMarker(
            MarkerOptions().position(coordinates).title(address.address).icon(
                BitmapDescriptorFactory.fromBitmap(
                    BitmapFactory.decodeResource(resources, R.mipmap.icon_location_red)
                )
            )
        )


    }

    private fun jumpOutMap(address: Address) {
        var choiceDialog = BottomChoiceDialog(this, MapNavigator.getMapChoice())
        choiceDialog.onChoiceListener = object : BaseBottomChoiceDialog.OnChoiceListener {
            override fun onChoice(type: String) {
                MapNavigator.mapNavigation(
                    this@MedicalCareOrderActivity,
                    type,
                    address.address,
                    address.getLat(),
                    address.getLon()
                )
            }

            override fun onCancel() {}
        }
        choiceDialog.show()

    }


    private fun initLocation() {
        //初始化定位
        mLocationClient = AMapLocationClient(CompassAppHelper.getApplication())
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener)
        //初始化AMapLocationClientOption对象
        mLocationOption = AMapLocationClientOption()
        //设置为签到模式（签到、出行、运动）
        mLocationOption.locationPurpose = AMapLocationClientOption.AMapLocationPurpose.SignIn
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy;
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.isNeedAddress = true;
        //获取最近3s内精度最高的一次定位结果：
        mLocationOption.isOnceLocationLatest = true;
        mLocationClient.setLocationOption(mLocationOption);
        //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
        mLocationClient.stopLocation();
        mLocationClient.startLocation();
    }

    /**
     * 判断是否有定位权限
     */
    private fun locationIsGranted() {
        //判断是否有权限
        if (XXPermissions.isGranted(
                this, Permission.ACCESS_FINE_LOCATION,
                Permission.ACCESS_COARSE_LOCATION
            )
        ) {
            showLocationDialog()
        } else {
            CommonMessageDialog.Builder(this)
                .setTitle(getStringFromResource(R.string.permission_explain))
                .setMessage(getStringFromResource(R.string.image_permission_location))
                .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))
                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    requestPermissions()
                    it?.dismiss()
                }.create().show()
        }
    }

    private fun showLocationDialog() {
        showLoading("正在定位请稍后...")
        initLocation()
    }


    /**
     * 请求权限
     */
    private fun requestPermissions() {
        XXPermissions.with(this)
            .permission(Permission.ACCESS_FINE_LOCATION)
            .permission(Permission.ACCESS_COARSE_LOCATION)
            .unchecked()
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        TipsToast.showTips("获取部分权限成功，但部分权限未正常授予")
                        return
                    }
                    showLocationDialog()
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {

                        TipsToast.showTips("被永久拒绝授权，请手动授予相关权限")
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(
                            this@MedicalCareOrderActivity,
                            permissions
                        )
                    } else {
                        TipsToast.showTips(com.compass.framework.R.string.default_agree_permission)
                    }
                }
            })
    }


    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mBinding.mapView.onSaveInstanceState(outState)
    }

    override fun onPause() {
        super.onPause()
        mBinding.mapView.onPause()
    }

    override fun onResume() {
        super.onResume()
        mBinding.mapView.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (this::mLocationClient.isInitialized) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy()
        }
        //销毁
        mBinding.mapView.onDestroy()
    }
}